package 动态代理;

import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class dongtai {
    public static void test(){
        PersonDao pDao = new PersonDaoImpl();
        PersonHandler handler = new PersonHandler(pDao);
        PersonDao proxy = (PersonDao) Proxy.newProxyInstance(pDao.getClass()
                .getClassLoader(), pDao.getClass().getInterfaces(), handler);
        proxy.say();
    }

    public static void main(String[] args) {
        dongtai.test();
    }
}
//创建一个接口
interface PersonDao {
    public void say();
}
//创建被代理类
class PersonDaoImpl implements PersonDao{
    @Override
    public void say() {
        System.out.println("time to eat");
    }
}
//创建一个动态代理
class PersonHandler implements InvocationHandler {
    private Object obj;
    public PersonHandler(Object obj){
        this.obj=obj;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("before");
        Object result = method.invoke(obj, args);
        System.out.println("after");
        return result;
    }
}




//具体测试
class PersonTest {
    @Test
    public void test(){
        PersonDao pDao = new PersonDaoImpl();
        PersonHandler handler = new PersonHandler(pDao);
        PersonDao proxy = (PersonDao) Proxy.newProxyInstance(pDao.getClass()
                .getClassLoader(), pDao.getClass().getInterfaces(), handler);
        proxy.say();
    }
}